# encoding: utf-8
"""
@author: 夏洛
@QQ: 1972386194
@file: 09-异步test.py
"""



'''
安卓 apk文件   压缩包 
应用层  --》 java去写的

a = "adsasdasd"  ---> pyton
String a  ="asdasdasdasdas"   ----> java 


写一个代码  变 小程序 app 网站
uniapp  跨平台  
fluter  


多线程  1条线程在跑任务    把多个任务分给多个线程
    5 5个线程  速度就提升5倍
'''

import time
import httpx

def main():
    with httpx.Client() as client:
        for i in range(100):
            res = client.get('https://www.baidu.com')
            print(f'第{i + 1}次请求，status_code = {res.status_code}')

if __name__ == '__main__':
    start = time.time()
    main()
    end = time.time()
    print(f'同步发送100次请求，耗时：{end - start}')
    # 2.403549909591675

import asyncio
import time
import httpx

async def req(client, i):
    # 对网站发请求 有耗时
    res = await client.get('https://www.baidu.com')
    print(f'第{i + 1}次请求，status_code = {res.status_code}')
    return res


async def main():
    async with httpx.AsyncClient() as client:
        task_list = []  # 任务列表
        for i in range(100):
            res = req(client, i)
            task = asyncio.create_task(res)  # 创建任务
            task_list.append(task)
        await asyncio.gather(*task_list)  # 收集任务

if __name__ == '__main__':
    start = time.time()
    asyncio.run(main())
    end = time.time()
    print(f'异步发送100次请求，耗时：{end - start}')

